import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


def save_classification_report(report_dict, filepath):
    df = pd.DataFrame(report_dict).transpose()
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    df.to_csv(filepath, index=True)


def plot_feature_importance(importances, feature_names, out_path, top_n=10, title=None):
    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    idx = np.argsort(importances)[::-1][:top_n]
    top_feats = [feature_names[i] for i in idx]
    top_imp = importances[idx]
    plt.figure(figsize=(8, 6))
    plt.barh(range(top_n), top_imp[::-1])
    plt.yticks(range(top_n), top_feats[::-1])
    plt.xlabel('Importance')
    if title:
        plt.title(title)
    plt.tight_layout()
    plt.savefig(out_path)
    plt.close()
